package com.zym.init.controller.backend;

import com.zym.init.core.annotation.ApiBackendRestController;
import com.zym.init.core.annotation.Log;
import com.zym.init.core.cache.StorageCache;
import com.zym.init.core.controller.BaseController;
import com.zym.init.core.domain.AjaxResult;
import com.zym.init.core.exception.ServiceException;
import com.zym.init.model.query.StorageQuery;
import com.zym.init.service.StorageService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.zym.init.core.constant.CommonConstant.FORBIDDEN_DELETE_STORAGE_CONFIG_IDS;

@Validated
@ApiBackendRestController
@RequestMapping(path = "/storage", produces = "application/json")
public class StorageController extends BaseController {
    final private StorageService storageService;

    public StorageController(StorageService storageService) {
        this.storageService = storageService;
    }

    /**
     * 获取列表
     */
    @Log(title = "获取存储配置列表")
    @PreAuthorize("@ss.hasPermission('system:storage:list')")
    @GetMapping
    public AjaxResult list(StorageQuery query) {
        return success("获取成功", storageService.getPage(query));
    }

    /**
     * 新增
     */
    @Log(title = "新增存储配置")
    @PreAuthorize("@ss.hasPermission('system:storage:add')")
    @PostMapping
    public AjaxResult add(@RequestBody @Validated(value = {StorageQuery.Add.class}) StorageQuery query) {
        return storageService.add(query) ? success("新增成功") : fail("新增失败");
    }

    /**
     * 编辑
     */
    @Log(title = "编辑存储配置")
    @PreAuthorize("@ss.hasPermission('system:storage:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated(value = {StorageQuery.Update.class}) StorageQuery query) {
        return storageService.edit(query) ? success("编辑成功") : fail("编辑失败");
    }

    /**
     * 删除
     */
    @Log(title = "删除存储配置")
    @PreAuthorize("@ss.hasPermission('system:storage:delete')")
    @DeleteMapping
    public AjaxResult delete(@RequestParam("ids") List<Long> ids) {
        for (Long id : FORBIDDEN_DELETE_STORAGE_CONFIG_IDS) {
            if (ids.contains(id)) {
                throw new ServiceException("不能删除本地存储配置");
            }
        }
        // 批量删除缓存
        StorageCache.del(ids);
        return storageService.removeBatchByIds(ids) ? success("删除成功") : fail("删除失败");
    }
}
